#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (C) 2012 Joseba García Etxebarria

"""This is the preferences dialog file for my block editor.
It relies in the UI file (created automagically by pyuic4
from the QT Designer project file)"""

import os,sys
from PyQt4 import QtCore, QtGui
from ui_preferences import Ui_Preferences
from preferences import preferences

# A class for managing the credits window
class dialog_preferences(QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)

        # Initialize preferences
        self.prefs = preferences()

        # Windows is stupid
        self.exeext=''
        if sys.platform.startswith('win'):
            self.exeext='.exe'

        # Get the stored preferences
        self.nastrandir          = self.prefs.get('nastrandir')
        self.nastranlibrarypath  = self.prefs.get('nastranlibrary')
        self.nastranpath         = self.prefs.get('nastranpath')
        self.nastranver          = self.prefs.get('nastranver')
        self.patrandir           = self.prefs.get('patrandir')
        self.patranpath          = self.prefs.get('patranpath')

        # This is always the same
        self.ui=Ui_Preferences()
        self.ui.setupUi(self)
        self.ui.button_NastranPath.clicked.connect(self.ChooseNastranPath)
        self.ui.button_NastranLibraryPath.clicked.connect(self.ChooseNastranLibraryPath)
        self.ui.button_PatranPath.clicked.connect(self.ChoosePatranPath)

        # Set the UI text
        self.ui.lineNastran.setText(self.nastrandir)
        self.ui.lineNastranLibrary.setText(self.nastranlibrarypath)
        self.ui.linePatran.setText(self.patrandir)

        # Show the dialog
        self.show()
        self.exec_()

    # Show the Nastran selector dialogs
    def ChooseNastranPath(self):
        nastrandir = QtGui.QFileDialog.getExistingDirectory(self, caption='Choose Nastran dir',
                                                            directory=self.nastrandir)
        nastrandir = str(nastrandir)
        # TODO: Determine Nastran version here
        for root, dirs, files in os.walk(os.path.join(nastrandir, 'bin')):
            for file in files:
                if file.startswith('nast'):
                    # Make sure the file's extension matches the executable one (if any) and remove it
                    if self.exeext and file.endswith('self.exeext'):
                        file = file.split('.')[0]

                    self.nastranver = file[len('nast'):]
                    try:
                        # Make sure we've got and integer there, but we want the string
                        int(self.nastranver)
                        self.nastranver = self.nastranver
                        self.ui.lineNastran.setText(nastrandir)
                    except ValueError:
                        self.nastranver = None

    # Show the Patran selector dialogs
    def ChoosePatranPath(self):
        patrandir = QtGui.QFileDialog.getExistingDirectory(self, caption='Choose Patran dir',
                                                           directory=self.patrandir)
        patrandir = str(patrandir)
        if os.path.isfile( os.path.join(patrandir, 'bin', 'patran'+self.exeext) ):
            self.ui.linePatran.setText(patrandir)

    # Show the Nastran Library selection dialog
    def ChooseNastranLibraryPath(self):
        nastranlibrary = QtGui.QFileDialog.getOpenFileName(self, "Path to nastran_library.pdf",
                                               directory = self.nastranlibrarypath,
                                               filter = "Nastran library models (*.pdf)")
        nastranlibrary = str(nastranlibrary)
        if os.path.isfile( nastranlibrary ):
                self.ui.lineNastranLibrary.setText(nastranlibrary)

    # Save the preferences
    def accept(self):
        "Save user proposed options"
        nastrandir     = str( self.ui.lineNastran.text() )
        patrandir      = str( self.ui.linePatran.text() )
        nastranlibrary = str( self.ui.lineNastranLibrary.text() )
        self.prefs.set('nastrandir', nastrandir)
        self.prefs.set('nastranver', self.nastranver)
        self.prefs.set('patrandir', patrandir)
        if os.path.isfile (nastranlibrary):
            self.prefs.set('nastranlibrary', nastranlibrary)
        self.hide()

    # Discard preferences
    def reject(self):
        self.hide()

